package com.walkline.zhihu;

import org.json.me.JSONObject;
import org.json.me.JSONTokener;

import com.walkline.app.ZhihuAppConfig;
import com.walkline.util.Function;
import com.walkline.util.network.HttpClient;
import com.walkline.util.network.MyConnectionFactory;
import com.walkline.zhihu.dao.ZhihuDailyStories;
import com.walkline.zhihu.dao.ZhihuHotStories;
import com.walkline.zhihu.dao.ZhihuSectionStories;
import com.walkline.zhihu.dao.ZhihuSections;
import com.walkline.zhihu.dao.ZhihuStoryDetails;
import com.walkline.zhihu.dao.ZhihuThemeStories;
import com.walkline.zhihu.dao.ZhihuThemes;
import com.walkline.zhihu.inf.DailyStories;
import com.walkline.zhihu.inf.HotStories;
import com.walkline.zhihu.inf.SectionStories;
import com.walkline.zhihu.inf.Sections;
import com.walkline.zhihu.inf.StoryDetails;
import com.walkline.zhihu.inf.ThemeStories;
import com.walkline.zhihu.inf.Themes;

public class ZhihuSDK
{
	protected HttpClient _http;

	public static ZhihuSDK getInstance() {return new ZhihuSDK();}

	protected ZhihuSDK()
	{
		MyConnectionFactory cf = new MyConnectionFactory();

		_http = new HttpClient(cf);
	}

	private DailyStories getDailyStories(JSONObject jsonObject) throws ZhihuException {return new ZhihuDailyStories(this, jsonObject);}
	public DailyStories getDailyStories(String date) throws ZhihuException {return getDailyStories(date, null, null);}
	public DailyStories getDailyStories(final String date, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						DailyStories result = null;
						result = getDailyStories(date);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			DailyStories result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				String api = "";

				api = (date != null ? ZhihuAppConfig.queryBeforeStoriesRequestURL + date : ZhihuAppConfig.queryLastStoriesRequestURL);
				jsonObject = doRequest(api);

				result = (jsonObject != null ? getDailyStories(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private HotStories getHotStories(JSONObject jsonObject) throws ZhihuException {return new ZhihuHotStories(this, jsonObject);}
	public HotStories getHotStories() throws ZhihuException {return getHotStories(null, null);}
	public HotStories getHotStories(final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						HotStories result = null;
						result = getHotStories();
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			HotStories result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(ZhihuAppConfig.queryHotStoriesRequestURL);

				result = (jsonObject != null ? getHotStories(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private StoryDetails getStoryDetails(JSONObject jsonObject) throws ZhihuException {return new ZhihuStoryDetails(this, jsonObject);}
	public StoryDetails getStoryDetails(String url) throws ZhihuException {return getStoryDetails(url, null, null);}
	public StoryDetails getStoryDetails(final String url, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						StoryDetails result = null;
						result = getStoryDetails(url);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			StoryDetails result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(url);

				result = (jsonObject != null ? getStoryDetails(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private StoryDetails getSectionStoryDetails(JSONObject jsonObject) throws ZhihuException {return new ZhihuStoryDetails(this, jsonObject);}
	public StoryDetails getSectionStoryDetails(String id) throws ZhihuException {return getSectionStoryDetails(id, null, null);}
	public StoryDetails getSectionStoryDetails(final String id, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						StoryDetails result = null;
						result = getSectionStoryDetails(id);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			StoryDetails result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(ZhihuAppConfig.queryStoryDetailsRequestURL + id);

				result = (jsonObject != null ? getSectionStoryDetails(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private Sections getSections(JSONObject jsonObject) throws ZhihuException {return new ZhihuSections(this, jsonObject);}
	public Sections getSections() throws ZhihuException {return getSections(null, null);}
	public Sections getSections(final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						Sections result = null;
						result = getSections();
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			Sections result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(ZhihuAppConfig.querySectionsRequestURL);

				result = (jsonObject != null ? getSections(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private SectionStories getSectionDetails(JSONObject jsonObject) throws ZhihuException {return new ZhihuSectionStories(this, jsonObject);}
	public SectionStories getSectionDetails(String id) throws ZhihuException {return getSectionDetails(id, null, null);}
	public SectionStories getSectionDetails(final String id, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						SectionStories result = null;
						result = getSectionDetails(id);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			SectionStories result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(ZhihuAppConfig.querySectionDetailsRequestURL + id);

				result = (jsonObject != null ? getSectionDetails(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private Themes getThemes(JSONObject jsonObject) throws ZhihuException {return new ZhihuThemes(this, jsonObject);}
	public Themes getThemes() throws ZhihuException {return getThemes(null, null);}
	public Themes getThemes(final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						Themes result = null;
						result = getThemes();
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			Themes result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(ZhihuAppConfig.queryThemesRequestURL);

				result = (jsonObject != null ? getThemes(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private ThemeStories getThemeDetails(JSONObject jsonObject) throws ZhihuException {return new ZhihuThemeStories(this, jsonObject);}
	public ThemeStories getThemeDetails(String id) throws ZhihuException {return getThemeDetails(id, null, null);}
	public ThemeStories getThemeDetails(final String id, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						ThemeStories result = null;
						result = getThemeDetails(id);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			ThemeStories result = null;
			JSONObject jsonObject = new JSONObject();

			try {
				jsonObject = doRequest(ZhihuAppConfig.queryThemesDetailsRequestURL + id);

				result = (jsonObject != null ? getThemeDetails(jsonObject) : null);
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}




//**************************************************************************************************
//
//             //              //      //    //      ////////////////            //      //        
//             //            //    //  //  //                    //          //  //  //  //        
// //////////  //          //////////  ////        //          //      //        //      //        
//     //    ////////////              //      //  //  //    //    //  //  ////////////  ////////  
//     //      //      //    ////////    ////////  //    //  //  //    //      ////    //    //    
//     //      //      //    //    //              //        //        //    //  ////    //  //    
//     //      //      //    ////////  //          //    //  //  //    //  //    //  //  //  //    
//     //      //      //    //    //  //    //    //  //    //    //  //      //        //  //    
//     ////////        //    ////////  //  //      //        //        //  //////////    //  //    
// ////      //        //    //    //  ////    //  //      ////        //    //    //      //      
//         //          //    //    //  //      //  //                  //      ////      //  //    
//       //        ////      //  ////    ////////  //////////////////////  ////    //  //      //  
//
//**************************************************************************************************

	public byte[] doRequestRAW(String imageUrl) throws ZhihuException
	{
		byte[] result = null;
		StringBuffer responseBuffer = null;

		try {
			responseBuffer = _http.doGet(imageUrl);				

			if ((responseBuffer == null) || (responseBuffer.length() <= 0))
			{
				result = null;
			} else {
				result = responseBuffer.toString().getBytes();				
			}
		} catch (Exception e) {
			throw new ZhihuException("[doRequestRAW Exception]\n\n" + e.getMessage());
		} catch (Throwable t) {
			throw new ZhihuException("[doRequestRAW Throwable]\n\n" + t.getMessage());
		}

		return result;
	}

	private JSONObject doRequest(String api) throws ZhihuException
	{
		StringBuffer responseBuffer = new StringBuffer();
		JSONObject result = new JSONObject();

		try {
			responseBuffer = _http.doGet(api);

			if ((responseBuffer == null) || (responseBuffer.length() <= 0))
			{
				result = null;
			} else {
				result = new JSONObject(new JSONTokener(new String(responseBuffer.toString().getBytes(), "utf-8")));
			}
		} catch (Exception e) {
			throw new ZhihuException(e.getMessage());
		} catch (Throwable t) {
			throw new ZhihuException(t.getMessage());
		}

		return result;
	}
}